import {createSlice} from '@reduxjs/toolkit';
import {DatasourceState} from '@/schemas/datasource.ts';
import {
    AllDsDescription,
    CreateDsFile,
    CreateDsServe,
    ListDatasource,
    LoadDatasource,
    SelectedDatasource
} from "@/service/datasource.ts";
import {Toast} from "@douyinfe/semi-ui"; // 确保路径正确

// 定义 user state 的初始值
const initialState: DatasourceState = {
    list: [],
    loading: false
};

const datasourceSlice = createSlice({
    name: 'datasource',
    initialState,
    reducers: {},
    extraReducers: (builder) => {

        [
            ListDatasource, CreateDsServe,
            CreateDsFile, LoadDatasource, SelectedDatasource,
            AllDsDescription
        ].forEach(thunk => {
            builder.addCase(thunk.pending, (state) => {
                state.loading = true
            })
            builder.addCase(thunk.rejected, (state, action) => {
                state.loading = false
                Toast.error(action.error.message || "数据操作出现未知错误")
            })
        })


        builder.addCase(AllDsDescription.fulfilled, (state, action) => {
            state.descriptions = action.payload
            state.loading = false
        })


        builder.addCase(ListDatasource.fulfilled, (state, action) => {
            state.list = action.payload;
            if (action.payload[0]) state.selected = action.payload[0]
            state.loading = false
        })
        builder.addCase(CreateDsFile.fulfilled, (state, action) => {
            state.list = action.payload
            if (action.payload[0]) state.selected = action.payload[0]
            state.loading = false
        })
        builder.addCase(CreateDsServe.fulfilled, (state, action) => {
            state.list = action.payload
            if (action.payload[0]) state.selected = action.payload[0]
            state.loading = false
        })
        builder.addCase(LoadDatasource.fulfilled, (state, action) => {
            state.selected = action.payload.selected
            state.sourceData = action.payload.sourceData
            state.loading = false
        })
        builder.addCase(SelectedDatasource.fulfilled, (state, action) => {
            state.selected = action.payload.selected
            state.sourceData = action.payload.sourceData
            state.loading = false
        })

    }
});

// 导出 actions
export const DATASOURCE = datasourceSlice.actions;

// 导出 reducer
export default datasourceSlice.reducer;